package com.sci.service.impl;

import com.sci.entity.User;
import com.sci.mapper.UserMapper;
import com.sci.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;

    @Override
    @Transactional
    public Boolean updateUsername(String wechatId, String newUsername) {
        User user = userMapper.selectById(wechatId);
        if(user == null) return false;
        user.setUserName(newUsername);
        return userMapper.updateById(user) > 0;
    }

    @Override
    @Transactional
    public Boolean deductBalance(String wechatId, Double amount) {
        return userMapper.deductBalance(wechatId, amount) > 0;
    }

    @Override
    @Transactional
    public Boolean register(User user) {
        if (userMapper.selectById(user.getWechatId()) != null) {
            return false;
        }

        user.setBalance(888.88);
        user.setPassword(sha256(user.getPassword()));
        return userMapper.insert(user) > 0;
    }

    private String sha256(String input) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hash = digest.digest(input.getBytes());
            StringBuilder hexString = new StringBuilder();

            for (byte b : hash) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }

            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }
}